package com.dingding.service.mall.dao.impl;

import java.math.BigDecimal;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;

import com.dingding.common.core.base.dao.impl.BaseDaoImpl;
import com.dingding.common.core.beans.Userintegral;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.service.mall.dao.IUserIntegralDao;

@Component("userIntegralDao")
public class UserIntegralDaoImpl extends BaseDaoImpl<Userintegral> implements IUserIntegralDao {

	/**
	 * 
	 * @Title: saveUserIntegralByNum
	 * @Description: 添加用户积分信息
	 * @param userLoginId
	 *            用户登录主键ID
	 * @author CHEHUANBO
	 * 
	 */
	public void addUserIntegral(String userLoginId) {

		Userintegral userintegral = new Userintegral();
		// 为用户账户表设置主键
		userintegral.setUsId(ToolUtil.getUid());
		// 用户登录ID
		userintegral.setLoginId(userLoginId);
		// 我的积分
		userintegral.setUserIntegral(new BigDecimal(0));
		// 账户状态
		userintegral.setUiStatus(1);
		try {
			// 向用户账户表插入一条记录
			super.save(userintegral);
		} catch (Exception e) {
			log.error("添加用户积分信息出现异常！", e);
		}

	}

	/**
	 * @Description:获取用户积分
	 * @param userLoginId 用户id
	 * @author fengshuonan
	 */
	public synchronized double getUserIntegral(String userLoginId) {

		Userintegral userintegral = null;

		Criterion criterion = Restrictions.eq("loginId", userLoginId);

		try {
			userintegral = this.queryCriteriaUnResult(criterion);
		} catch (Exception e) {
			log.error("获取用户积分失败！UserIntegralDaoImpl:getUserIntegral()", e);
		}

		if (userintegral != null) {
			return userintegral.getUserIntegral().doubleValue();
		}

		return 0;
	}

	/**
	 * @Description: 修改用户积分
	 * @param userId 用户id
	 * @param inte 用户剩余积分
	 * @author fengshuonan
	 * @return void
	 * @Override
	 */
	public void updateUserInte(String userId, BigDecimal inte) {

		Userintegral userintegral = null;

		Criterion criterion = Restrictions.eq("loginId", userId);

		try {
			userintegral = this.queryCriteriaUnResult(criterion);
		} catch (Exception e) {
			log.error("修改用户积分失败！UserIntegralDaoImpl:updateUserInte()", e);
		}

		if (userintegral != null) {
			userintegral.setUserIntegral(inte);
		}
	}
}
